#include "IntegralHistSet.h"

#include <iostream>
using namespace std;

//////////////////////////////////////////////////////////////////
// IntegralHistSet Object										//
//////////////////////////////////////////////////////////////////

// Constructor for set of integral histograms
IntegralHistSet::IntegralHistSet(ImageSet* imgset, bool label)
{
	cout << "CONSTRUCTING HISTOGRAMS!!!" << endl;
	// Create head of list
	_head = new IntegralHistNode;
	_head->_label = label;
	_head->_hist = new IntegralHist(imgset->_head->_image);
	_head->next = NULL;
	_head->previous = NULL;
	_tail = _head;
	_n = 1;
	if(_head->_label)
	{
		_pos = 1;	_neg = 0;
	}
	else
	{
		_pos = 0;	_neg = 1;
	}

	// Initialise pointer at the top of image set and iterate 
	// through list.
	ImageNode* temp = imgset->_head->next;
	while(temp)
	{
		_tail->next = new IntegralHistNode;
		_tail->next->_label = label;
		_tail->next->_hist = new IntegralHist(temp->_image);
		_tail->next->next = NULL;
		_tail->next->previous = _tail;
		if(_tail->next->_label)
			_pos++;
		else
			_neg++;
		_tail = _tail->next;
		temp = temp->next;
		_n++;
	}
	cout << "Finished building histograms" << endl;
}

// Copy constructor for set of integral histograms
IntegralHistSet::IntegralHistSet(const IntegralHistSet &init)
{
	// Copy number of images across
	_n = init._n;
	_pos = init._pos;
	_neg = init._neg;

	// Check if we need to copy stuff across
	if(init._head)
	{
		// Initialise the beginning of the list with the correct image
		_head = new IntegralHistNode;
		_head->_label = init._head->_label;
		if(init._head->_hist)
			_head->_hist = new IntegralHist(*(init._head->_hist));
		_head->next = NULL;
		_head->previous = NULL;
		_tail = _head;

		// Traverse the list and copy everything across
		IntegralHistNode* temp = init._head;
		while(temp->next)
		{
			_tail->next = new IntegralHistNode;
			_tail->next->_label = temp->next->_label;
			_tail->next->_hist = new IntegralHist(*(temp->next->_hist));
			_tail->next->previous = _tail;
			_tail = _tail->next;
			temp = temp->next;
		}
	}
	else
	{
		_head = NULL;
		_tail = NULL;
	}
}

// Destructor for set of integral histograms
IntegralHistSet::~IntegralHistSet()
{
	cout << "woop" << endl;
	// Loop while we are not at the head node
	if(_tail)
		while(_tail->previous)
		{
			// Jump back one
			_tail = _tail->previous;
			// Delete everything from the node at the end of the list
			if(_tail->next->_hist)
			{
				delete _tail->next->_hist;
			}
			if(_tail->next)
				delete _tail->next;
		}

	// Delete the head node
	if(_head)
	{
		if(_head->_hist)
		{
			delete _head->_hist;
		}
		delete _head;
	}
}